package com.base.vistter.iframe.inverter.controller;

import com.base.vistter.iframe.bean.Result;
import com.base.vistter.iframe.properties.IframeProperties;
import com.base.vistter.iframe.utils.RedisUtils;
import com.wf.captcha.*;
import com.wf.captcha.base.Captcha;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/captcha")
@Slf4j
public class CaptchaController {

    @Resource(name = "iframeProperties")
    private IframeProperties iframeProperties;
    @GetMapping
    public Result<Map<String, String>> captcha(String key) {
        if (StringUtils.isNotEmpty(key)) {
            RedisUtils.delete(key);
        }
        Map<String, String> result = new HashMap<String, String>();
        Captcha captcha = null;
        switch (iframeProperties.getCaptchaType()) {
            case 2:
                captcha = new ChineseCaptcha(130, 40);
                break;
            case 3:
                captcha = new ChineseGifCaptcha(130, 40);
                break;
            case 4:
                captcha = new GifCaptcha(130, 40);
                break;
            case 5:
                captcha = new SpecCaptcha(130, 40);
                break;
            default:
                captcha = new ArithmeticCaptcha(130, 40);
                break;
        }

        String uuid = UUID.randomUUID().toString();
        System.out.println(captcha.text());
        RedisUtils.setString(uuid , captcha.text() , 2 , TimeUnit.MINUTES);

        result.put("uuid", uuid);
        result.put("img", captcha.toBase64());
        return Result.ok(result);
    }

}
